package com.hex.es.service.impl;

import com.hex.es.annotation.EsBuildParamTypeInfo;
import com.hex.es.aop.AbstractEsAop;
import com.hex.es.enums.StatisticsTypeEnum;
import com.hex.es.service.ParamBuildInterface;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

/**
 * @description: 分组聚合统计参数构建器
 * @author: Hex
 * @date: 2019/11/20 16:29
 */
@Slf4j
@Service
public class ParamBuildGorupByImpl extends AbstractEsAop implements ParamBuildInterface {

    private static final String GROUP_PARAM = "group_param";

    @Override
    public void paramBuild(Object key, Object value, BoolQueryBuilder boolQueryBuilder, NativeSearchQueryBuilder searchQueryBuilder, EsBuildParamTypeInfo esBuildParamTypeInfo) {
        if (StringUtils.isNotEmpty(esBuildParamTypeInfo.groupByFieldName()) && PARAM_THREAD_LOCAL.get().get(GROUP_PARAM)==null) {
            TermsAggregationBuilder termsBuilder = AggregationBuilders.terms(lineToHump(esBuildParamTypeInfo.groupByFieldName())).field(humpToUnderline(esBuildParamTypeInfo.groupByFieldName())).size(Integer.MAX_VALUE);
            String[] statisticsAnotherName = esBuildParamTypeInfo.statisticsAnotherName();
            String[] statisticsFieldName = esBuildParamTypeInfo.statisticsFieldName();
            StatisticsTypeEnum[] statisticsType = esBuildParamTypeInfo.statisticsType();
            for (int i=0;i<statisticsFieldName.length;i++){
                if (statisticsType[i].equals(StatisticsTypeEnum.MAX)) {
                    termsBuilder.subAggregation(AggregationBuilders.max(statisticsAnotherName[i]).field(statisticsFieldName[i]));
                } else if (statisticsType[i].equals(StatisticsTypeEnum.MIN)) {
                    termsBuilder.subAggregation(AggregationBuilders.min(statisticsAnotherName[i]).field(statisticsFieldName[i]));
                } else if (statisticsType[i].equals(StatisticsTypeEnum.SUM)) {
                    termsBuilder.subAggregation(AggregationBuilders.sum(statisticsAnotherName[i]).field(statisticsFieldName[i]));
                } else if (statisticsType[i].equals(StatisticsTypeEnum.AVG)) {
                    termsBuilder.subAggregation(AggregationBuilders.avg(statisticsAnotherName[i]).field(statisticsFieldName[i]));
                }
            }
            searchQueryBuilder.addAggregation(termsBuilder);
            PARAM_THREAD_LOCAL.get().put(GROUP_PARAM,esBuildParamTypeInfo.groupByFieldName());
        }
    }
}
